package me.zhengjie.tools.rest


import me.zhengjie.tools.domain.AlipayConfig
import me.zhengjie.tools.utils.AlipayUtils

import me.zhengjie.logging.annotation.Log
import me.zhengjie.tools.service.AlipayService
import me.zhengjie.tools.domain.vo.TradeVo
import me.zhengjie.tools.utils.AliPayStatusEnum

import io.swagger.v3.oas.annotations.Hidden
import io.swagger.v3.oas.annotations.media.Schema

import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity

import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import java.nio.charset.StandardCharsets


/**
 * @author Kuki Wu
 * @date 2018-12-31
 */
@RestController
@RequestMapping("/api/aliPay")
@Schema(description = "工具：支付宝管理")
class AliPayController(alipayUtils: AlipayUtils, alipayService: AlipayService) {
    private val alipayUtils:AlipayUtils =  alipayUtils
    private val alipayService: AlipayService = alipayService
    @GetMapping
    fun get(): ResponseEntity<AlipayConfig> {
        return ResponseEntity(alipayService.find(), HttpStatus.OK)
    }

    @Log("配置支付宝")
    @Schema(description = "配置支付宝")
    @PutMapping
    fun payConfig(@Validated @RequestBody alipayConfig: AlipayConfig): ResponseEntity<*> {
        alipayConfig.id = 1L
        alipayService.update(alipayConfig)
        return ResponseEntity<Any?>(HttpStatus.OK)
    }

    @Log("支付宝PC网页支付")
    @Schema(description = "PC网页支付")
    @PostMapping(value = ["/toPayAsPC"])
    @Throws(
        Exception::class
    )
    fun toPayAsPC(@Validated @RequestBody trade: TradeVo): ResponseEntity<String> {
        val alipay = alipayService.find()
        trade.outTradeNo = alipayUtils.orderCode
        val payUrl = alipayService.toPayAsPC(alipay, trade)
        return ResponseEntity.ok(payUrl)
    }

    @Log("支付宝手机网页支付")
    @Schema(description = "手机网页支付")
    @PostMapping(value = ["/toPayAsWeb"])
    @Throws(
        Exception::class
    )
    fun toPayAsWeb(@Validated @RequestBody trade: TradeVo): ResponseEntity<String> {
        val alipay = alipayService.find()
        trade.tradeNo = alipayUtils.orderCode
        val payUrl = alipayService.toPayAsWeb(alipay, trade)
        return ResponseEntity.ok(payUrl)
    }

    @Hidden
    @GetMapping("/return")
    @me.zhengjie.common.annotation.AnonymousAccess
    @Schema(description = "支付之后跳转的链接")
    fun returnPage(request: HttpServletRequest, response: HttpServletResponse): ResponseEntity<String> {
        val alipay = alipayService.find()
        response.contentType = "text/html;charset=" + alipay!!.charset
        //内容验签，防止黑客篡改参数
        return if (alipayUtils.rsaCheck(request, alipay)) {
            //商户订单号
            val outTradeNo = String(
                request.getParameter("out_trade_no").toByteArray(StandardCharsets.ISO_8859_1),
                StandardCharsets.UTF_8
            )
            //支付宝交易号
            val tradeNo = String(
                request.getParameter("trade_no").toByteArray(StandardCharsets.ISO_8859_1),
                StandardCharsets.UTF_8
            )
            println("商户订单号$outTradeNo  第三方交易号$tradeNo")

            // 根据业务需要返回数据，这里统一返回OK
            ResponseEntity("payment successful", HttpStatus.OK)
        } else {
            // 根据业务需要返回数据
            ResponseEntity(HttpStatus.BAD_REQUEST)
        }
    }

    @Hidden
    @RequestMapping("/notify")
    @me.zhengjie.common.annotation.AnonymousAccess
    @Schema(description = "支付异步通知(要公网访问)，接收异步通知，检查通知内容app_id、out_trade_no、total_amount是否与请求中的一致，根据trade_status进行后续业务处理")
    fun notify(request: HttpServletRequest): ResponseEntity<*> {
        val alipay = alipayService.find()
        val parameterMap = request.parameterMap
        //内容验签，防止黑客篡改参数
        if (alipayUtils.rsaCheck(request, alipay)) {
            //交易状态
            val tradeStatus = String(
                request.getParameter("trade_status").toByteArray(StandardCharsets.ISO_8859_1),
                StandardCharsets.UTF_8
            )
            // 商户订单号
            val outTradeNo = String(
                request.getParameter("out_trade_no").toByteArray(StandardCharsets.ISO_8859_1),
                StandardCharsets.UTF_8
            )
            //支付宝交易号
            val tradeNo = String(
                request.getParameter("trade_no").toByteArray(StandardCharsets.ISO_8859_1),
                StandardCharsets.UTF_8
            )
            //付款金额
            val totalAmount = String(
                request.getParameter("total_amount").toByteArray(StandardCharsets.ISO_8859_1),
                StandardCharsets.UTF_8
            )
            //验证
            if (tradeStatus == AliPayStatusEnum.SUCCESS.value || tradeStatus == AliPayStatusEnum.FINISHED.value) {
                // 验证通过后应该根据业务需要处理订单
            }
            return ResponseEntity<Any?>(HttpStatus.OK)
        }
        return ResponseEntity<Any?>(HttpStatus.BAD_REQUEST)
    }
}